﻿using Microsoft.Data.Sqlite;
using SendMailServer.Database;
using SendMailServer.User;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SendMailServer
{
    internal class ProgressRecorder
    {
        public ResMsg HandlerMsg(string key, string filterStr)
        {
            if (key == "RecordProgress")
            {
                try
                {
                    if (filterStr == null) { filterStr = ""; }
                    if (filterStr.EndsWith(",desktop"))
                    {
                        filterStr = filterStr.Substring(0, filterStr.Length - ",desktop".Length);
                    }
                    var ts = filterStr.Split(',');
                    var userName = ts[0];
                    if (userName == "未登录用户")
                    {
                        return null;
                    }
                    var taskId = ts[1];
                    var modelName = ts[2];
                    var progressValue = ts[3];
                    var msg = ts[4];

                    WriteRecordToDB(userName, taskId, modelName, progressValue, msg);

                    return new ResMsg()
                    {
                        AppName = "desktop",
                        Content = "ProgressRecorderOK",
                        IsOk = true,
                        UseSelfResponse = true,
                    };
                }
                catch (Exception err)
                {
                    Logger.WriteLine("SendWebhookMsg错误：" + err.Message + ";" + err.StackTrace);
                }
                return null;
            }
            if(key== "GetProgress")
            {
                if (filterStr == null) { filterStr = ""; }
                if (filterStr.EndsWith(",desktop"))
                {
                    filterStr = filterStr.Substring(0, filterStr.Length - ",desktop".Length);
                }
                var userName = filterStr;
                var records = ReadRecordsFromDB(userName);

                return new ResMsg()
                {
                    AppName = "desktop",
                    Content = records,
                    IsOk = true,
                    UseSelfResponse = true,
                };
            }
            return null;
        }

        private void WriteRecordToDB(string userName, string taskID, string modelName, string progressValue, string msg)
        {
            StringBuilder stringBuilder = new StringBuilder();
            Microsoft.Data.Sqlite.SqliteConnection conn = null;
            Microsoft.Data.Sqlite.SqliteCommand cmd = null;
            SqliteDataReader dr = null;
            StringBuilder sb = new StringBuilder();
            try
            {
                
                using (conn = DatabaseHelper.BuildConnection())
                {
                    var searchSql = "select count(*) from DataProcessProgress where userName=\"" + userName + "\" and taskID=\"" + taskID + "\"";
                    cmd = new Microsoft.Data.Sqlite.SqliteCommand(searchSql, conn);
                    var or = cmd.ExecuteScalar();
                    if (or.ToString() == "0")
                    {
                        string sql = "insert into DataProcessProgress(userName,taskID,modelName,progressValue,msg,recordTime)  values(";
                        sb.Append(sql);
                        sb.Append("\"" + userName + "\",");
                        sb.Append("\"" + taskID + "\",");
                        sb.Append("\"" + modelName + "\",");
                        sb.Append("\"" + progressValue + "\",");
                        sb.Append("\"" + msg + "\",");
                        sb.Append("\"" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\")");
                        cmd = new Microsoft.Data.Sqlite.SqliteCommand(sb.ToString(), conn);
                        cmd.ExecuteNonQuery();
                    }
                    else
                    {
                        sb.Append(" update DataProcessProgress set ");
                        sb.Append(" modelName = \"" + modelName + "\",");
                        sb.Append(" progressValue = \"" + progressValue + "\",");
                        sb.Append(" msg= \"" + msg + "\",");
                        sb.Append(" recordTime= \"" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\" ");
                        sb.Append(" where userName =\"" + userName + "\" and taskID=\"" + taskID + "\"");

                        cmd = new Microsoft.Data.Sqlite.SqliteCommand(sb.ToString(), conn);
                        cmd.ExecuteNonQuery();
                    }
                       
                }
            }
            catch (Exception err)
            {
                Logger.WriteLine("WriteRecordToDB发生异常:" + err.Message + ";" + sb.ToString());
            }
            finally
            {
                if (dr != null)
                {
                    dr.Close();
                }
                if (cmd != null)
                {
                    cmd.Dispose();
                }
                if (conn != null)
                {
                    conn.Close();
                    conn.Dispose();
                }
            }
        }

        private string ReadRecordsFromDB(string userName)
        {
            StringBuilder stringBuilder = new StringBuilder();
            Microsoft.Data.Sqlite.SqliteConnection conn = null;
            Microsoft.Data.Sqlite.SqliteCommand cmd = null;
            SqliteDataReader dr = null;
            try
            {
                using (conn = DatabaseHelper.BuildConnection())
                {
                    StringBuilder sb = new StringBuilder();
                    string sql = "select * from DataProcessProgress where userName like ";
                    sb.Append(sql);
                    sb.Append("\"" + userName + "%\"");
                    sb.Append(" order by recordTime desc");
                    cmd = new Microsoft.Data.Sqlite.SqliteCommand(sb.ToString(), conn);
                    dr = cmd.ExecuteReader();

                    int readCount = 0;

                    while (dr.Read())
                    {
                        for(var i = 0; i < 6; i++)
                        {
                            if (i != 0)
                            {
                                stringBuilder.Append(",");
                            }
                            stringBuilder.Append(dr.GetString(i));
                        }
                            
                        stringBuilder.Append("$");
                        readCount++;
                        if (readCount > 20)
                        {
                            break;
                        }
                    }
                }
                return stringBuilder.ToString();
            }
            catch (Exception err)
            {
                Logger.WriteLine("ReadRecordsFromDB发生异常:" + err.Message + ";" + err.StackTrace);
                return null;
            }
            finally
            {
                if (dr != null)
                {
                    dr.Close();
                }
                if (cmd != null)
                {
                    cmd.Dispose();
                }
                if (conn != null)
                {
                    conn.Close();
                    conn.Dispose();
                }
            }
        }
    }
}